package com.tracelog.core.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 请求工具类
 *
 * @author tracelog
 * @since 1.0.0
 */
public class RequestUtils {

    /**
     * 从请求中获取请求体内容
     *
     * @param request 请求对象
     * @return 请求体内容
     */
    public static String getRequestBody(HttpServletRequest request) {
        String body = "";
        
        // 如果是ContentCachingRequestWrapper类型，则直接从缓存中获取
        if (request instanceof ContentCachingRequestWrapper) {
            ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) request;
            byte[] buffer = wrapper.getContentAsByteArray();
            if (buffer.length > 0) {
                body = new String(buffer, StandardCharsets.UTF_8);
            }
        } else {
            // 尝试从输入流中读取
            try {
                body = IoUtil.read(request.getInputStream(), StandardCharsets.UTF_8);
            } catch (IOException e) {
                // 忽略异常
            }
        }
        
        return body;
    }
    
    /**
     * 判断是否为JSON请求
     *
     * @param request 请求对象
     * @return 是否为JSON请求
     */
    public static boolean isJsonRequest(HttpServletRequest request) {
        String contentType = request.getContentType();
        return StrUtil.isNotBlank(contentType) && contentType.contains("application/json");
    }
    
    /**
     * 判断是否为文件上传请求
     *
     * @param request 请求对象
     * @return 是否为文件上传请求
     */
    public static boolean isMultipartRequest(HttpServletRequest request) {
        String contentType = request.getContentType();
        return StrUtil.isNotBlank(contentType) && contentType.contains("multipart/form-data");
    }
} 